package a66weding.com.jiehuntong.activity.me;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.SetHomeActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeHeadBean;
import a66weding.com.jiehuntong.beans.MeMarriedDayBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.WXbean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.CallbackListeners;
import a66weding.com.jiehuntong.widgets.CircularImage;
import a66weding.com.jiehuntong.widgets.wheelview.OnWheelChangedListener;
import a66weding.com.jiehuntong.widgets.wheelview.WheelView;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.ArrayWheelAdapter;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.NumericWheelAdapter;

/**
 * 我的界面-个人信息
 */
public class MeUserinfoActivity extends MeBaseActivity implements View.OnClickListener, OnWheelChangedListener , CompoundButton.OnCheckedChangeListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mSexTV;
    private TextView mHome;
    private TextView mMarriedDay;
    private TextView mAge;
    private RelativeLayout mHeaderRightRlay;
    private RelativeLayout mNameRlay;
    private RelativeLayout mAddressRlay;
    private RelativeLayout mResumeRlay;
    private RelativeLayout mSexRlay;
    private RelativeLayout mMarryRlay;
    private RelativeLayout mBirthRlay;
    private RelativeLayout mHomeRlay;
    private RelativeLayout mHeadRlay;
    private Button photoBtn;
    private Button cameraBtn;
    private Button quxiaoBtn;
    private Dialog dialog;
    private TextView mNickName;
    private WheelView mViewYear;
    private WheelView mViewMonth;
    private WheelView mViewDistrict;
    private PopupWindow mDatePopupWindow;
    private int mSelectYear;
    private int mSelectDay;
    private int mStartYear = 2016;
    private int mCurrentYear;
    private int year;
    private int month;
    private int day;
    private int mCurrentMonth;
    private int mCurrentDay;
    private int isex;
    //头像的名字
    public  static String  HEAD_PHOTO_NAME = "head_image.jpg";
    private CircularImage mUserPhoto;
    private Bitmap bitmap;
    private CallbackListeners callbackListeners;
    private String weddingDate;
    private static final int PERMISSION_CAMERA=5;
    private static final int PERMISSION_SDCARD=4;
    private static final int TAKE_PHOTO=2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_userinfo);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeUserinfoActivity", this);

        initview();
    }

    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);
        mNameRlay = (RelativeLayout) findViewById(R.id.rlay_me_userinfo_name);
        mAddressRlay = (RelativeLayout) findViewById(R.id.rlay_me_userinfo_address);
        mResumeRlay = (RelativeLayout) findViewById(R.id.rlay_me_userinfo_resume);
        mSexRlay = (RelativeLayout) findViewById(R.id.rlay_me_userinfo_sex);
        mMarryRlay = (RelativeLayout) findViewById(R.id.rl_marry_date);
        mBirthRlay = (RelativeLayout) findViewById(R.id.rl_birth_date);
        mHomeRlay = (RelativeLayout) findViewById(R.id.rl_home);
        mHeadRlay = (RelativeLayout) findViewById(R.id.rl_me_head);
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mSexTV = (TextView) findViewById(R.id.tv_sex);
        mNickName = (TextView) findViewById(R.id.tv_me_nickname);
        mHome = (TextView) findViewById(R.id.tv_home);
        mMarriedDay = (TextView) findViewById(R.id.tv_married_day);
        mAge = (TextView) findViewById(R.id.tv_age);
        mUserPhoto = (CircularImage) findViewById(R.id.iv_me_head);

        mBackContentTv.setText("我的");
        mHeaderTitleTv.setText("个人信息");
        mHeaderRightRlay.setVisibility(View.GONE);

        mNameRlay.setOnClickListener(this);
        mAddressRlay.setOnClickListener(this);
        mResumeRlay.setOnClickListener(this);
        mSexRlay.setOnClickListener(this);
        mBackLay.setOnClickListener(this);
        mMarryRlay.setOnClickListener(this);
        mBirthRlay.setOnClickListener(this);
        mHomeRlay.setOnClickListener(this);
        mHeadRlay.setOnClickListener(this);

        bitmap = FileUtil.getBitmapFromDisk(HEAD_PHOTO_NAME,this);
        if (bitmap != null) {
            Drawable drawable = new BitmapDrawable(bitmap);
            mUserPhoto.setImageDrawable(drawable);
        }

    }

    /**
     * 用户可见的调用的方法
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Name())){
            mNickName.setText(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Name());
        }
        int sex = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Sex();
        if(sex == 1) {  //如果性别的值为1,设置为女
            mSexTV.setText("女");
        } else if(sex == 0){
            mSexTV.setText("男");    //否则设置为男
        }
        if(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Address() != null &&
                !(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Address().equals(""))) {  //如果登录的家乡内容不为空串
            mHome.setText(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Address()); //只要一显示界面就去获取家乡
        }
        if(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_WeddingDate() != null &&
                !(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_WeddingDate().equals(""))) {  //如果登录的婚期内容不为空串
            mMarriedDay.setText(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_WeddingDate()); //只要一显示界面就去获取婚期
        }
        if(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Age() != null &&
                !(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Age().equals(""))) {  //如果登录的年龄内容不为空串
            mAge.setText(DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Age()); //只要一显示界面就去获取年龄
        }
        if (DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto() != null){
            x.image().bind(mUserPhoto, DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto());
        }
    }
    /**
     * Dialog设置封面
     */
    protected static Uri tempUri;
    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);

        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            showPhoto();
                dialog.dismiss();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCamera();
                dialog.dismiss();
            }
        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * 调用系统相册
     */
    private void showPhoto() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SDCARD);
        }else{
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 1);
        }
    }
    /**
     * 拍照
     */
    private void showCamera() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        }else{

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //下面这句指定调用相机拍照后的照片存储的路径
            File imgFile = new File(FileUtil.getImgFile(this), "touxiang.jpg");
            if (imgFile.exists()){
                imgFile.delete();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            startActivityForResult(intent, TAKE_PHOTO);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //下面这句指定调用相机拍照后的照片存储的路径
                File imgFile = new File(FileUtil.getImgFile(this), "touxiang.jpg");
                if (imgFile.exists()){
                    imgFile.delete();
                }

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
                startActivityForResult(intent, TAKE_PHOTO);

            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }else if(requestCode ==PERMISSION_SDCARD){
            if(grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);
            }else{
                CUtils.showToast("请打开手机SD卡权限后在操作");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                if (data!=null){
                    startPhotoZoom(data.getData());
                }
                break;
            // 如果是调用相机拍照时
            case TAKE_PHOTO:
                    File temp = new File(FileUtil.getImgFile(this), "touxiang.jpg");
                    startPhotoZoom(Uri.fromFile(temp));
//                }
                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case 8:

                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom1(Uri uri) {
        if (uri == null) {
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }
    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            File saveFile=new File(FileUtil.getImgFile(this),HEAD_PHOTO_NAME);

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                fileOutputStream.write(byteArray,0,byteArray.length);
                fileOutputStream.flush();
                fileOutputStream.close();

            } catch (Exception e) {

                e.printStackTrace();
            }
            //上传服务器
            uploadfile(saveFile);
            /**
             * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上
             * 传到服务器，QQ头像上传采用的方法跟这个类似
             */
            mUserPhoto.setImageDrawable(drawable);
            //将bitmap 直接写入指定的文件里

        }
    }

    /** * android上传文件到服务器
     * @param file 需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    public  String uploadFile(File file,String RequestURL) {
        String result="";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10*100000); conn.setConnectTimeout(10*100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if(file!=null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8"+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if(res==200)
                {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    reader.close();

                    return result;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * POST WeddingMobileApiSD/PostUpBookPicture?Token={Token}&mobileStr={mobileStr}&bookId={bookId}
     */
    private void uploadfile(final File saveFile) {
        //图片上传地址
        String phone = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_MobilePhone();
        String id = ""+DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        String oldUrl= UrlDealUtil.getRealUrlNoIdApiSd(RequestCode.POSTUPLOAD);
        final String url = oldUrl + phone;
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                try {
                    Gson mgson = new Gson();
                    MeHeadBean meHeadBean = mgson.fromJson(result,MeHeadBean.class);
                    if (meHeadBean != null){
                        //更新内存
                        DataWareHourse.getInstance().getmUser().getData().get(0).setNvc_TitlePhoto(meHeadBean.getResult().getUrlField());
                        //更新本地缓存
                        CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
                    }
                    x.image().bind(mUserPhoto, DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto());
                    callbackListeners.playResume();
                    sendBroadCase();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void setCallbackListeners(CallbackListeners callbackListeners) {
        this.callbackListeners = callbackListeners;
    }

    private void sendBroadCase(){
        Intent intent = new Intent();
        intent.setAction("aaa.bbb.ccc");
        sendOrderedBroadcast(intent, null);
    }


    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.llay_header_back:         //点击返回按钮，关闭界面
                setResult(MainActivity.getResultForMeCode,intent);
                finish();
                break;
            case R.id.rlay_me_userinfo_name:    //选中昵称后打开设置昵称界面
                intent.setClass(this, MeUserNicknameActivity.class);
                startActivity(intent);
                break;
            case R.id.rlay_me_userinfo_address: //选中地址后打开地址管理界面
                intent.setClass(this, MeUserShippingaddressActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_marry_date: //选中我的婚期,打开设置婚期
                if (mDatePopupWindow != null) {
                    mDatePopupWindow.dismiss();
                    mDatePopupWindow = null;
                }
                showdatePopupWindow(view);
                break;
            case R.id.rl_birth_date: //选中我的年龄,打开设置年龄
                intent.setClass(this, MeSetAgeActivity.class);
                startActivity(intent);
                break;
            case R.id.rlay_me_userinfo_resume:  //打开个人简介界面
                intent.setClass(this, MeUserResumeActivity.class);
                startActivity(intent);
                break;
            case R.id.rlay_me_userinfo_sex:     //点击性别弹出选择性别对话框
                showSexDialog();
                break;
            case R.id.tv_cancel:  //取消设置日期
                if (mDatePopupWindow != null) {
                    mDatePopupWindow.dismiss();
                    mDatePopupWindow = null;
                }
                break;
            case R.id.tv_confim:  //确认设置日期
                // 点击设置日期,发送网络请求
                weddingDate = year + "-" +  month + "-" + day;
                String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_WEDDINGDATE);
                HashMap<String,String> requestParams=new HashMap<String,String>();
                requestParams.put("WeddingDate",""+ weddingDate);
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        this, MeMarriedDayBean.class, RequestCode.UPDATE_WEDDINGDATE, requestParams);
                HttpHandleUtil.executeCommonPost(this,httpRequestBean);
                break;
            case R.id.rl_home:  // 打开设置家乡
                intent.setClass(MeUserinfoActivity.this, SetHomeActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_me_head:  // 打开编辑头像
                showDialog();
                break;
        }

    }

    /**
     * 设置婚期的popupWindow
     * @param view
     */
    private void showdatePopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_tools_holiday_day_date, null);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_cancel);
        TextView mConfimTv = (TextView) contentView.findViewById(R.id.tv_confim);
        mViewYear = (WheelView) contentView.findViewById(R.id.id_hour);
        mViewMonth = (WheelView) contentView.findViewById(R.id.id_minute);
        mViewDistrict = (WheelView) contentView.findViewById(R.id.id_day);

        mCancelTv.setOnClickListener(this);
        mConfimTv.setOnClickListener(this);

        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加change事件
        mViewYear.addChangingListener(this);
        // 添加change事件
        mViewMonth.addChangingListener(this);

        setUpData();
        mDatePopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        mDatePopupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));

        //点击空白处时，隐藏掉pop窗口
        mDatePopupWindow.setTouchable(true);

        mDatePopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        mDatePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    }

    /**
     * 设置婚期的日期
     */
    private void setUpData() {
        getTime();
        String[] years = new String[11];
        for (int i = 0; i < 11; i++) {
            years[i] = 2016 + i + "年";
        }
        ArrayWheelAdapter yearWheelAdapter = new ArrayWheelAdapter(this, years);

        String[] months = new String[12];
        for (int i = 0; i < 12; i++) {
            months[i] = 1 + i + "月";
        }
        ArrayWheelAdapter montnWheelAdapter = new ArrayWheelAdapter<String>(this, months);

        mViewYear.setViewAdapter(yearWheelAdapter);
        mViewMonth.setViewAdapter(montnWheelAdapter);

        // 设置可见条目数量
        mViewDistrict.setVisibleItems(2);
        mViewYear.setVisibleItems(7);
        mViewMonth.setVisibleItems(7);

        int index = mCurrentYear - mStartYear;
        mViewYear.setCurrentItem(index);

        mViewDistrict.setCurrentItem(0);
        mViewYear.setCurrentItem(0);
        mViewMonth.setCurrentItem(mCurrentMonth);

        mViewYear.setCyclic(false); //设置是否可以不断转动
        mViewMonth.setCyclic(true);

        updateDays();

    }
    /**
     * 设置每天的方法
     */
    private void updateDays() {
        year = mViewYear.getCurrentItem() + mStartYear;
        month = mViewMonth.getCurrentItem() + 1;

        String[] mDays = null;
        int lastDay = 30;

        if (month == 2) {
            if (isLeapYear(year)) {
                mDays = new String[29];
                for (int i = 1; i < 29; i++) {
                    mDays[i] = i + "日";
                }
                lastDay = 29;
            } else {
                mDays = new String[28];
                for (int i = 1; i < 28; i++) {
                    mDays[i] = i + "日";
                }
                lastDay = 28;
            }
        } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            mDays = new String[31];
            for (int i = 1; i < 31; i++) {
                mDays[i] = i + "日";
            }
            lastDay = 31;

        } else {
            mDays = new String[30];
            for (int i = 1; i < 30; i++) {
                mDays[i] = i + "日";
            }
            lastDay = 30;
        }
        if (mDays == null) {
            mDays = new String[]{""};
        }
        day = mViewDistrict.getCurrentItem() + 1;

        NumericWheelAdapter dayWheelAdapter = new NumericWheelAdapter(this, 1, lastDay);

        mViewDistrict.setViewAdapter(dayWheelAdapter);

        mViewDistrict.setVisibleItems(7);

        if (mSelectDay > mDays.length - 1) {
            mSelectDay = mDays.length - 1;
        }

        mViewDistrict.setCurrentItem(mSelectDay);

        mViewDistrict.setCyclic(true);

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewYear) {
            mSelectYear = newValue;

            if ((mStartYear + mSelectYear) < mCurrentYear) {
                mViewYear.setCurrentItem(mCurrentYear - mStartYear);
            }
            updateDays();

        } else if (wheel == mViewMonth) {

            updateDays();
        } else if (wheel == mViewDistrict) {
            mSelectDay = newValue;
            updateDays();
        }

    }

    /**
     * 判断是否是闰年
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        boolean flag = false;
        if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取系统时间
     */
    public void getTime(){
        Calendar c = Calendar.getInstance();
//        取得系统日期:
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mSelectDay=mCurrentDay-1;

        //取得系统时间：
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int  minute = c.get(Calendar.MINUTE);

    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof MeMarriedDayBean) {
            MeMarriedDayBean meMarriedDayBean = (MeMarriedDayBean) data;
            if ("0000".equals(meMarriedDayBean.getResCode())){
                CUtils.showToast("婚期设置成功");
                //更新内存
                DataWareHourse.getInstance().getmUser().getData().get(0).setNvc_WeddingDate(weddingDate);
                //更新本地缓存
                CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
                mMarriedDay.setText(weddingDate);
                if (mDatePopupWindow != null) {
                    mDatePopupWindow.dismiss();
                    mDatePopupWindow = null;
                }
            }
        } else if (data instanceof CommonResultBean) {
            CommonResultBean commonResultBean = (CommonResultBean) data;
            if ("0000".equals(commonResultBean.getResCode())) {
                mSexTV.setText("男");
                CUtils.showToast("性别设置成功");
                //更新内存
                DataWareHourse.getInstance().getmUser().getData().get(0).setI_Sex(isex);
                //更新本地缓存
                CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
            }
        } else if ((data instanceof  WXbean)) {
            WXbean wXbean = (WXbean) data;
            if ("0000".equals(wXbean.getResCode())) {
                mSexTV.setText("女");
                CUtils.showToast("性别设置成功");
                //更新内存
                DataWareHourse.getInstance().getmUser().getData().get(0).setI_Sex(isex);
                //更新本地缓存
                CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(MainActivity.getResultForMeCode,intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    /**
     * 设置男女的dialog
     */
    private void showSexDialog() {
        View view = getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);        // 男
        cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);      // 女
        quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);      // 取消

        photoBtn.setText("男");
        cameraBtn.setText("女");

        photoBtn.setOnClickListener(new View.OnClickListener() {            // 点击男
            @Override
            public void onClick(View v) {
//                isex = 1;
                isex = 0;
                // 发起网络请求,将性别信息发送到服务器
                String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_SEX);
                HashMap<String,String> requestParams=new HashMap<String,String>();
                requestParams.put("Sex",""+ isex);
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        MeUserinfoActivity.this, CommonResultBean.class, RequestCode.UPDATE_SEX, requestParams);
                HttpHandleUtil.executeCommonPost(MeUserinfoActivity.this,httpRequestBean);
                dialog.dismiss();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {           // 点击女
            @Override
            public void onClick(View v) {
//                isex = 0;
                isex = 1;
                // 发起网络请求,将性别信息发送到服务器
                String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_SEX);
                HashMap<String,String> requestParams=new HashMap<String,String>();
                requestParams.put("Sex",""+ isex);
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        MeUserinfoActivity.this, WXbean.class, RequestCode.UPDATE_SEX, requestParams);
                HttpHandleUtil.executeCommonPost(MeUserinfoActivity.this,httpRequestBean);
                dialog.dismiss();
            }
        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCancelable(true);
        dialog.show();
    }
}
